package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 查询分类是否存在
func CategoryExist(c *gin.Context) {

}

// 添加分类
func AddCategory(c *gin.Context) {
	var data model.Category
	_ = c.ShouldBindJSON(&data)
	code = model.CheckCate(data.Name)
	if code == errmsg.SUCCESS {
		code = model.CreateCate(&data)
	}
	if code == errmsg.ERROR_CATENAME_USED {
		code = errmsg.ERROR_CATENAME_USED
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

// 查询单个分类下的文章
func GetCategoryToArticle(c *gin.Context) {}

// 查询分类列表
func GetCategoryList(ctx *gin.Context) {
	// strconv.Atoi 字符串转换成 int
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}

	if pageNum == 0 {
		pageNum = 1
	}

	//if pageSize == 0 {
	//	pageSize = -1 //因gorm提供 一个方法
	//}
	//if pageNum == 0 {
	//	pageNum = -1 //因gorm提供 一个方法
	//}
	cateList, total := model.GetCateList(pageSize, pageNum)
	fmt.Println("cateList", cateList)
	fmt.Println("total", total)
	code = errmsg.SUCCESS
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    cateList,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})

}

// 修改分类
func EditCategory(c *gin.Context) {
	var data model.Category
	// 获取需要编辑用户的id
	id, _ := strconv.Atoi(c.Param("id"))
	// 前端的json数据绑定到用户模型上
	c.ShouldBindJSON(&data)
	code = model.CheckCate(data.Name)
	if code == errmsg.SUCCESS {
		model.EditCate(id, &data)
	}
	if code == errmsg.ERROR_CATENAME_USED {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})

}

// 删除分类
func DeleteCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteCate(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"data":    "数据删除成功！",
	})
}
